package org.shoukaiseki.kakaroto.utils;

import org.apache.commons.lang3.StringUtils;
import org.shoukaiseki.common.utils.NumberUtils;
import org.shoukaiseki.supersaiyan.common.core.domain.SysUser;
import org.shoukaiseki.supersaiyan.common.core.domain.model.LoginUser;
import org.shoukaiseki.supersaiyan.common.utils.SecurityUtils;

import java.util.Set;

/**
 *
 **/
public class TokenUserUtils {

    public static LoginUser getLoginUser(){
        return SecurityUtils.getLoginUser();
    }

    public static SysUser getUser(){
        return SecurityUtils.getLoginUser().getUser();
    }

    public static String getUserName(){
        return SecurityUtils.getUsername();
    }

    public static Long getUserId(){
        SysUser user = getUser();
        if (user==null) {
            throw new RuntimeException("未登录,无法获取用户信息");
        }
        return user.getUserId();
    }


    public static boolean isAdmin(){
        return SecurityUtils.isAdmin(getUserId());
    }

    public static boolean isSystem(){
        return SecurityUtils.isSystem(getUserId());
    }

    //管理方式是否开启
    public static boolean isManageMode(){
        return getLoginUser().getAdminConfig().isManageMode();
    }

    //管理方式是否开启
    public static boolean isDebug(){
        return getLoginUser().getAdminConfig().isDebug();
    }

    //提示消息使用 调试模式是否开启
    public static boolean isDebugMessage(){
        return getLoginUser().getAdminConfig().isDebugMessage();
    }

    /**
     * 提示消息使用 调试模式是否开启
     * 如果未登录则未返回false
     * return true: 已开启消息调试模式
     */
    public static boolean isDebugMessageTryCatch(){
        try{
            return getLoginUser().getAdminConfig().isDebugMessage();
        }catch (Throwable t){
            return false;
        }
    }


    //是否开启开发模式
    public static boolean isDevelopMode() {
        return getLoginUser().getAdminConfig().isDevelopMode();
    }

    /**
     * 判断是否拥有某项权限
     * @param permission            需要判断的权限
     * @return
     */
    public static boolean hasPermission(String permission){
        return hasPermission(getLoginUser(),permission);
    }

    /**
     * 判断是否拥有某项权限
     * @param loginUser             登录的用户
     * @param permission            需要判断的权限
     * @return
     */
    public static boolean hasPermission(LoginUser loginUser,String permission){
        if (isAdmin()) {
            return true;
        }
        return hasPermission(loginUser.getPermissions(),permission);
    }

    public static boolean hasPermission(Set<String> permissions, String permission){
        for (String s : permissions) {
            if (StringUtils.equals(s,permission)) {
                return true;
            }
        }
        return false;
    }

    //是否为当前登录人
    public static boolean isLoginUserId(Long userId){
        return NumberUtils.isEquals(userId,getUserId());
    }

}
